package com.frxuexi.park2303.user

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.frxuexi.base.http.Const
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.park2303.R
import com.frxuexi.park2303.databinding.ActivityLoginBinding
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/app/LoginActivity")
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding, UserIntent, UserViewModel>() {

    override fun getVM(): UserViewModel {
        return viewModels<UserViewModel>().value
    }

    override fun getBind(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }

    override fun initData() {
        vm.userData.observe(this) {
            SPUtils.getInstance().apply {
                put(Const.TOKEN, it.token)
                put(Const.UID, it.id)
                put(Const.UNAME, it.username)
                put(Const.ROLE, it.roleid)
            }
            start(it.roleid)
        }
    }

    fun start(role: Int) {
//        if (role == 19) {
//            ARouter.getInstance().build("/app/ShopActivity").navigation()
//        } else if(role==32){
        if(role!=-1) {
            ARouter.getInstance().build("/app/MainActivity").navigation()
            finish()
        }
//        }
    }

    override fun initView() {
        val role = SPUtils.getInstance().getInt(Const.ROLE, -1)
        start(role)
        binding.btnLogin.setOnClickListener {
            val uname = binding.loginUname.text.toString()
            val pass = binding.loginPass.text.toString()
            vm.sendIntent(UserIntent.login(uname, pass))
        }

        binding.loginRegister.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
//            finish()
        }

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val uname = intent?.getStringExtra("uname")
        val pass = intent?.getStringExtra("pass")

        binding.loginUname.setText(uname)
        binding.loginPass.setText(pass)
    }

}